package day_14.homework;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ck
 * @date2021/8/22 22:22
 */
@SuppressWarnings("all")
public class Cinema implements Runnable{
    //定义票数
    private int tickets = 1000;
    //创建锁对象
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        //死循环
        while (true){
            //上锁，记住一定要记得释放锁 且上锁的操作必须是在try上面 紧领着try语句
            lock.lock();
            try {
                //结束条件
                if (tickets == 0) {
                    break;
                }else {
                    //休眠
//                    Thread.sleep(3000);
                    tickets--;
                    System.out.println(Thread.currentThread().getName()+"已经卖出第"+(1000-tickets)+"张电影票");
                }
                //finally语句必定执行，因为释放锁的操作是必须要执行的
                //所以将释放锁的操作也放在finally语句中
            } finally {
                lock.unlock();
            }
        }
    }
}
